/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.montecristo.posmobile;

import java.util.ArrayList;
import java.util.Currency;
import java.util.List;

import org.montecristo.posmobile.previo.base.ManagerDB;
import org.montecristo.posmobile.previo.clases.encuesta.Applicacion;
import org.montecristo.posmobile.previo.clases.encuesta.Seccion;
import org.montecristo.posmobile.R;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.SpinnerAdapter;



@TargetApi(11)
public class NewsReaderActivity extends FragmentActivity
        implements HeadlinesFragment.OnHeadlineSelectedListener,
                   CompatActionBarNavListener,
                   OnClickListener  {
    boolean mIsDualPane = false;
    HeadlinesFragment mHeadlinesFragment;
    ArticleFragment mArticleFragment;
    List<Seccion> listaAux = new ArrayList<Seccion>();
    ManagerDB manager;
    int mCatIndex = 0;
    int mArtIndex = 0;
    String idApp;
    private Applicacion app;
    Seccion mCurrentCat;
    final String CATEGORIES[] = { "| Secciones |"};
    String nomSeccion = "";
   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT < 11) {
			//Quitamos barra de titulo de la aplicacion
			this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		}
        setContentView(R.layout.main_layout);
        idApp=getIntent().getStringExtra("idApp");
        manager = new ManagerDB(this);
        app= manager.getApplicacionById(idApp);
        listaAux=manager.getSeccionesBYEncuesta(app.getIdEncuesta());
        mHeadlinesFragment = (HeadlinesFragment) getSupportFragmentManager().findFragmentById(R.id.headlines);
        mArticleFragment = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.article);
        View articleView = findViewById(R.id.article);
        mIsDualPane = articleView != null && articleView.getVisibility() == View.VISIBLE;
        mHeadlinesFragment.setOnHeadlineSelectedListener(this);
        int catIndex = savedInstanceState == null ? 0 : savedInstanceState.getInt("catIndex", 0);
        setUpActionBar(mIsDualPane, catIndex);
        mHeadlinesFragment.setSelectable(mIsDualPane);
        restoreSelection(savedInstanceState);
        Button catButton = (Button) findViewById(R.id.categorybutton);
        if (catButton != null) {
            catButton.setOnClickListener(this);
        }
    }

    void restoreSelection(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            setNewsCategory(savedInstanceState.getInt("catIndex", 0));
            if (mIsDualPane) {
                int artIndex = savedInstanceState.getInt("artIndex", 0);
                mHeadlinesFragment.setSelection(artIndex);
                onHeadlineSelected(artIndex);
            }
        }
    }

   @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        restoreSelection(savedInstanceState);
    }


   @TargetApi(11)
	public void setUpActionBar(boolean showTabs, int selTab) {
        if (Build.VERSION.SDK_INT < 11) {
            return;
        }

        android.app.ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayHomeAsUpEnabled(true);
        CompatActionBarNavHandler handler = new CompatActionBarNavHandler(this);
        if (showTabs) {
            actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
            int i;
            actionBar.addTab(actionBar.newTab().setText("").setTabListener(handler));
            actionBar.setSelectedNavigationItem(selTab);
        }
        else {
        	actionBar.setTitle("| Secciones |");
            //actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST);
            //SpinnerAdapter adap = new ArrayAdapter<String>(this, R.layout.actionbar_list_item,CATEGORIES);
            //actionBar.setListNavigationCallbacks(adap, handler);
        }

        // Show logo instead of icon+title.
        actionBar.setDisplayUseLogoEnabled(true);
    }

   @Override
    public void onStart() {
        super.onStart();
        setNewsCategory(0);
    }


    void setNewsCategory(int categoryIndex) {
        mCatIndex = categoryIndex;
        mCurrentCat = listaAux.get(categoryIndex);
        mHeadlinesFragment.loadCategory(categoryIndex);
        if (mIsDualPane) {
            mArticleFragment.displayArticle(mCurrentCat.getIdSeccion(),idApp);
            android.app.ActionBar actionBar = getActionBar();
            actionBar.getSelectedTab().setText(mCurrentCat.Encabezado.toString());
        }
        
        Button catButton = (Button) findViewById(R.id.categorybutton);
        if (catButton != null) {
            catButton.setText(mCurrentCat.Encabezado.toString());
        }
    }


   @Override
    public void onHeadlineSelected(int index) {
        mArtIndex = index;
        mCurrentCat = listaAux.get(index);
        if (mIsDualPane) {
        	android.app.ActionBar actionBar = getActionBar();
            actionBar.getSelectedTab().setText(mCurrentCat.Encabezado.toString());
            mArticleFragment.displayArticle(mCurrentCat.getIdSeccion(),idApp);
        }
        else {
            // use separate activity
            Intent i = new Intent(this, ArticleActivity.class);
            i.putExtra("idApp", idApp);
            i.putExtra("idSecc", mCurrentCat.getIdSeccion());
            startActivity(i);
        }
    }


   @Override
    public void onCategorySelected(int catIndex) {
        setNewsCategory(catIndex);
        //mArticleFragment.displayArticle(mCurrentCat.Encabezado,idApp);
    }

    /** Save instance state. Saves current category/article index. */
   @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("catIndex", mCatIndex);
        outState.putInt("artIndex", mArtIndex);
        super.onSaveInstanceState(outState);
    }


   @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Select a Category");
        builder.setItems(CATEGORIES, new DialogInterface.OnClickListener() {
           @Override
            public void onClick(DialogInterface dialog, int which) {
                setNewsCategory(which);
            }
        });
        AlertDialog d = builder.create();
        d.show();
    }
    
   @Override
    public void startActivity(Intent intent) {
    	// TODO Auto-generated method stub
    	super.startActivity(intent);
    	overridePendingTransition(R.anim.animation_leave,R.anim.animation_enter);
    }
    
   @Override
    public void onBackPressed() {
        super.onBackPressed();        
        overridePendingTransition(R.anim.animation_leaver,R.anim.animation_enterr);
    }
   
}
